package com.jdew.thkj.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.jdew.thkj.R;
import com.jdew.thkj.adapter.MainFragmentPageAdapter;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.bean.VersionBean;
import com.jdew.thkj.dialog.CommonDialog;
import com.jdew.thkj.fragment.DiscountsFragment;
import com.jdew.thkj.fragment.HomeFragment;
import com.jdew.thkj.fragment.HuiFenCicleFragment;
import com.jdew.thkj.fragment.MineFragment;
import com.jdew.thkj.fragment.SuperCoachFragment;
import com.jdew.thkj.manager.ActivityManagerUtils;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.utils.APKVersionCodeUtils;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.PermisionUtils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.view.NoScrollViewPager;
import com.king.app.updater.AppUpdater;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author yangyang
 * @date 2017/9/11
 */

public class MainActivity extends BaseActivity {
    @Bind(R.id.viewpager)
    public NoScrollViewPager viewpager;
    @Bind(R.id.main_rgp)
    public RadioGroup rgp;
    @Bind(R.id.home)
    RadioButton home;
    private MainFragmentPageAdapter adapter;
    private List<Fragment> fragemnts;
    public RadioButton rb;
    private long exitTime = 0;

    @Override
    public int bindLayout() {
        return R.layout.activity_main;
    }

    @Override
    public void initView(View view) {
        initView();
    }

    public void initView() {
        PermisionUtils.verifyStoragePermissions(MainActivity.this);
        fragemnts = new ArrayList<>();
        fragemnts.add(HomeFragment.newInstance());
        fragemnts.add(DiscountsFragment.newInstance());
        fragemnts.add(SuperCoachFragment.newInstance());
        fragemnts.add(HuiFenCicleFragment.newInstance());
        fragemnts.add(MineFragment.newInstance());
        viewpager.setNoScroll(true);
        viewpager.setOffscreenPageLimit(5);
        setListener();
        setAdapter();
        rb = (RadioButton) rgp.getChildAt(0);
        rb.setChecked(true);
        home.setOnClickListener(this);
    }

    private void setListener() {
        //RadioGroup的事件监听
        rgp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                for (int index = 0; index < rgp.getChildCount(); index++) {
                    RadioButton rb = (RadioButton) rgp.getChildAt(index);
                    if (rb.isChecked()) {
                        viewpager.setCurrentItem(index, false);
                        break;
                    }
                }
            }
        });
    }

    private void setAdapter() {
        //实例化适配器
        adapter = new MainFragmentPageAdapter(getSupportFragmentManager(), fragemnts);
        //设置适配器
        viewpager.setAdapter(adapter);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long now = System.currentTimeMillis() - exitTime;
            if (now > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
                return true;
            } else {
                ActivityManagerUtils.finishAllActivity();
            }
        }
        return super.onKeyDown(keyCode, event);
    }


    public void GetBanben() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetBanben(RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<VersionBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(VersionBean bean) {
                if (bean.getCode().equals("0")) {
                    String versionCode = bean.getData().getBnumber();
                    String tit = bean.getData().getContentOne();
                    if (!versionCode.equals(APKVersionCodeUtils.getVersionCode(MainActivity.this) + "")) {
                        checkVersion(tit);
                    }
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        sp = getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        if (sp.getBoolean("update", true)) {
            GetBanben();
        }
        if (!sp.getString("Alias", "").equals("")) {
            SetUserLevel();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void checkVersion(String title) {
        SimpleDateFormat sdf = new SimpleDateFormat("yy.MM.dd");
        Date d = new Date();
        String dateNowStr = sdf.format(d);

        //这里不发送检测新版本网络请求，直接进入下载新版本安装
        final CommonDialog.Builder builder = new CommonDialog.Builder(this, true);
        builder.setTitle(dateNowStr + " 系统更新公告");
        builder.setMessage(title);
        builder.setCancelable(false);
        builder.setPositiveButton("立即升级", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.dismiss();
                new AppUpdater.Builder()
                        .serUrl("http://taolehui.oss-cn-hangzhou.aliyuncs.com/taolehui.apk")
                        .setFilename("taolehui.apk")
                        .build(MainActivity.this)
                        .start();
            }
        });
        builder.setNegativeButton(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                editor.putBoolean("update", false);
                editor.apply();
                builder.dismiss();
            }
        });
        builder.create().show();
    }


    public void SetUserLevel() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetUserlevel(sp.getString("Alias", ""), RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserPhone" + sp.getString("Alias", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                Log.d("sssss", e.toString());
            }

            @Override
            public void onNext(JSONObject obj) {
                if (obj.getString("code").equals("0")) {
                    if (!sp.getString("SpareTwo", "").equals(obj.getString("data"))) {
                        editor.putString("userName", "");
                        editor.putString("token", "");
                        editor.putString("SpareTwo", "");
                        editor.putString("Alias", "");
                        editor.apply();
                        if (obj.getString("data").equals("2")) {
                            commomDialog("恭喜您升级为高级惠员，请重新登陆!");
                        } else if (obj.getString("data").equals("0")) {
                            commomDialog("恭喜您升级为超级教练，请重新登陆!");
                        } else if (obj.getString("data").equals("4")) {
                            commomDialog("恭喜您升级为子公司，请重新登陆!");
                        } else if (obj.getString("data").equals("5")) {
                            commomDialog("恭喜您升级为股东，请重新登陆!");
                        }
                    }
                } else if (obj.getString("code").equals("-1")) {
                    ToastUtils.getInstance(MainActivity.this).showMessage(obj.getString("message"));
                    editor.putString("userName", "");
                    editor.putString("token", "");
                    editor.putString("SpareTwo", "");
                    editor.putString("Alias", "");
                    editor.putString("userPhone", "");
                    editor.apply();
                }
            }
        });
    }

    public void commomDialog(String Message) {
        new CommonDialog.Builder(this)
                .setTitle("提示")
                .setMessage(Message)
                .setMessageGravity()
                .setCanceledOnTouchOutside(false)
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivity(new Intent(MainActivity.this, LoginActivity.class));
                    }
                }).show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.home:{
                EventBus.getDefault().post("toHome");
            }
            break;
        }
    }
}